#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -f /etc/os-release ]; then
   echo "Linux system."
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   if [ -f ~/.bash_profile ]; then
      source ~/.bash_profile
    fi
elif current_os_is_windows; then
   echo "Windows system."
fi

APP_TARGET_DIR_NAME="NotaGen"

echo "lmdprogress:3"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_conda.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_TARGET_DIR_NAME}"
echo $CURRENT_APP_PATH
mkdir -p "$CURRENT_APP_PATH"

echo "lmdprogress:8"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

echo "lmdprogress:12"

export GIT_HOST=${GITHUB_PROXY}"https://github.com"
export GIT_REPO_URL=${GIT_HOST}/ElectricAlexis/NotaGen
export GIT_REPO_BRANCH="main"
export LOCAL_REPO_PATH="$CURRENT_APP_PATH"
sh "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/git_clone_and_fetch.sh"

echo "lmdprogress:20"

cd "$CURRENT_APP_PATH"

# conda update -n base conda -y

echo "lmdprogress:25"

export CONDA_PREFIX="./venv"

if [ -d "$CONDA_PREFIX" ]; then
    echo "found ./venv. remove it. "
    rm -rf "$CONDA_PREFIX"
fi

export PYTHON_VER_ENV=3.10
conda_create_env $CONDA_PREFIX python=$PYTHON_VER_ENV -y

echo "lmdprogress:28"

echo "lmdprogress:34"

cd "$CURRENT_APP_PATH"

echo "lmdprogress:43"
if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
  # conda_run_pip_install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu
  source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_mac.sh"
elif current_os_is_windows; then
  source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_multi_method.sh"
fi

conda_run_pip_install modelscope huggingface_hub hf_xet accelerate optimum typing-extensions gradio

echo "lmdprogress:44"

conda_run_pip_install -r requirements.txt

echo "lmdprogress:60"
if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

export TORCH_HOME="./tmp_torch_home"
export HF_HOME="./tmp_hf_home"
export HF_ENDPOINT="https://hf-mirror.com"

echo "start download models"

conda_run_cmd modelscope download "ElectricAlexis/NotaGen" "weights_notagenx_p_size_16_p_length_1024_p_layers_20_h_size_1280.pth" --local_dir "gradio"

echo "lmdprogress:100"
